@extends('frontend.layouts.user_panel')

@section('panel_content')

    <div class="aiz-titlebar mt-2 mb-4">
      <div class="row align-items-center">
        <div class="col-md-6">
            <h1 class="h3">{{ translate('Products') }}</h1>
        </div>
      </div>
    </div>

    <!--<div class="row gutters-10 justify-content-center">
        @if (addon_is_activated('seller_subscription'))
            <div class="col-md-4 mx-auto mb-3" >
                <div class="bg-grad-1 text-white rounded-lg overflow-hidden">
                  <span class="size-30px rounded-circle mx-auto bg-soft-primary d-flex align-items-center justify-content-center mt-3">
                      <i class="las la-upload la-2x text-white"></i>
                  </span>
                  <div class="px-3 pt-3 pb-3">
                      <div class="h4 fw-700 text-center">{{ max(0, Auth::user()->seller->remaining_uploads) }}</div>
                      <div class="opacity-50 text-center">{{  translate('Remaining Uploads') }}</div>
                  </div>
                </div>
            </div>
        @endif

        <div class="col-md-4 mx-auto mb-3" >
            <a href="{{ route('seller.products.upload')}}">
              <div class="p-3 rounded mb-3 c-pointer text-center bg-white shadow-sm hov-shadow-lg has-transition">
                  <span class="size-60px rounded-circle mx-auto bg-secondary d-flex align-items-center justify-content-center mb-3">
                      <i class="las la-plus la-3x text-white"></i>
                  </span>
                  <div class="fs-18 text-primary">{{ translate('Add New Product') }}</div>
              </div>
            </a>
        </div>

        <div class="col-md-4 mx-auto mb-3" >
            <a href="{{ route('seller.products')}}?from=web">
              <div class="p-3 rounded mb-3 c-pointer text-center bg-white shadow-sm hov-shadow-lg has-transition">
                  <span class="size-60px rounded-circle mx-auto bg-secondary d-flex align-items-center justify-content-center mb-3">
                      <i class="las la-plus la-3x text-white"></i>
                  </span>
                  <div class="fs-18 text-primary">产品库</div>
              </div>
            </a>
        </div>


        @if (addon_is_activated('seller_subscription'))
        @php
            $seller_package = \App\Models\SellerPackage::find(Auth::user()->seller->seller_package_id);
        @endphp
        <div class="col-md-4">
            <a href="{{ route('seller_packages_list') }}" class="text-center bg-white shadow-sm hov-shadow-lg text-center d-block p-3 rounded">
                @if($seller_package != null)
                    <img src="{{ uploaded_asset($seller_package->logo) }}" height="44" class="mw-100 mx-auto">
                    <span class="d-block sub-title mb-2">{{ translate('Current Package')}}: {{ $seller_package->getTranslation('name') }}</span>
                @else
                    <i class="la la-frown-o mb-2 la-3x"></i>
                    <div class="d-block sub-title mb-2">{{ translate('No Package Found')}}</div>
                @endif
                <div class="btn btn-outline-primary py-1">{{ translate('Upgrade Package')}}</div>
            </a>
        </div>
        @endif

    </div>-->

    <div class="card">
        <div class="card-header">
            <div class="container-fluid">
                <div class="row">
                    <div class="col-12">
                        <h5 class="h6">{{ translate('All Products') }}</h5>
                    </div>
                </div>
                <form class="row" action="" method="GET">
                    <input type="hidden" name="from" value="{{ request()->input('from', '') }}" />
                    <div class="col-12 p-2">
                        <input type="text" class="form-control" id="search" name="search" @isset($search) value="{{ $search }}" @endisset placeholder="{{ translate('Search product') }}">
                    </div>
                    <div class="col-12 p-2">
                        <select name="category_id" class="form-control form-control-lg aiz-selectpicker"
                                data-live-search="true" onchange="filterProducts()">
                            <option value="">{{ translate('All Categories') }}</option>
                            @foreach (\App\Models\Category::all() as $key => $category)
                                <option value="{{ $category->id }}">{{ $category->getTranslation('name') }}</option>
                            @endforeach
                        </select>
                    </div>

                    <div class="col-12 p-2">
                        <div class="row">
                            <div class="col-6 text-center">
                                <button type="submit" class="btn btn-success fs-12 w-150px" >{{ translate('Confirm') }}</button>
                            </div>
                            <div class="col-6 text-center">
                                <button type="button" class="btn btn-primary fs-12 w-150px disabled" data-target="batchPublishModal" onclick="showModal(this)">{{ translate('Batch published') }}</button>
                            </div>
                        </div>
                    </div>
                </form>
            </div>


        </div>

        <div class="card-body">
            <table class="table aiz-table mb-0">
                <thead>
                    <tr>
                        <th><input type="checkbox" name="checkboxAll" value="1" onclick="checkAll(this)"/></th>
                        <!--<th>#</th>-->
                        <th width="30%">{{ translate('Name')}}</th>
                        <th data-breakpoints="md">{{ translate('Category')}}</th>
                        <th data-breakpoints="md">{{ translate('Current Qty')}}</th>
                        <th>{{ translate('Lowest Price')}}</th>

                        <th data-breakpoints="md" class="text-right">{{ translate('Options')}}</th>
                    </tr>
                </thead>

                <tbody>
                    @foreach ($products as $key => $product)
                        <tr>
                            <td><input type="checkbox" name="id[]" value="{{ $product->id }}" onclick="singleCheck(this)"/></td>
                            <!--<td>{{ ($key+1) + ($products->currentPage() - 1)*$products->perPage() }}</td>-->
                            <td>
                                <div class="row gutters-5 w-200px w-md-300px mw-100">
                                <div class="col-auto">
                                    <img src="{{ uploaded_asset($product->thumbnail_img)}}" alt="Image" class="size-50px img-fit">
                                </div>
                                <div class="col">
                                    <span class="text-muted text-truncate-2">{{ $product->getTranslation('name') }}</span>
                                </div>
                            </div>
                            </td>
                            <td>
                                @if ($product->category != null)
                                    {{ $product->category->getTranslation('name') }}
                                @endif
                            </td>
                            <td>
                                @php
                                    $qty = 0;
                                    foreach ($product->stocks as $key => $stock) {
                                        $qty += $stock->qty;
                                    }
                                    echo $qty;
                                @endphp
                            </td>
                            <td>{{ $product->unit_price }}</td>

                            <td class="text-right">

                                     <a href="javascript:docopy({{$product->id}},'{{route('products.duplicate', $product->id)}}',{{ $product->unit_price }})" class="btn btn-soft-success btn-icon btn-circle btn-sm"  title="{{ translate('Duplicate') }}">
    							   <i class="las la-copy"></i>
    						  </a>


                          </td>
                        </tr>
                    @endforeach
                </tbody>
            </table>
            <div class="aiz-pagination">
                {{ $products->withQueryString()->links() }}
          	</div>
        </div>
    </div>



    <div class="modal fade" id="batchPublishModal" data-backdrop="static" role="dialog" aria-hidden="true" >
    	<div class="modal-dialog" role="document" style="min-width: 40%;">
    		<div class="modal-content h-100">
    			<div class="modal-header pb-0 bg-light">
    				<div class="uppy-modal-nav">{{ translate('Batch published') }}</div>
    				<button type="button" class="close" data-dismiss="modal" aria-label="Close">
    					<span aria-hidden="true"></span>
    				</button>
    			</div>
    			<div class="modal-body" style="min-height: 180px;">
    			    <!--<div>
    			        <label><input type="checkbox" name="is_modify" value="1"/><span style="margin-left: 4px;">{{translate('Batch modify products price')}}</span></label>
    			    </div>-->
    			    <div class="row">
    			       <!--<div class="col-md-4">
    			            <select class="form-control aiz-selectpicker" name="modify_op" data-live-search="false">
                            <option value="0">{{translate('Remain unchanged')}}</option>
                            <option value="1">{{translate('Increment price')}}</option>
                            <option value="-1">{{translate('Decrement price')}}</option>
                        </select>
    			       </div>-->
    			       <div class="col-md-6">
        			        <div class="input-group mb-3">
                              <input type="text" class="form-control" placeholder="{{translate('Please fill in the premium percentage')}}" name="modify_price">
                              <div class="input-group-append">
                                <span class="input-group-text">%</span>
                              </div>
                            </div>
                            <span style="color: red; font-size: 14px; font-weight: 400">{{ translate('Premium range') }}</span>
                        </div>
    			    </div>

    			</div>
    			<div class="modal-footer justify-content-between bg-light">
    			    <div style="flex: 1;">
    			        <span style="color: red; font-size: 14px; font-weight: 400; " id="selected_tips" data-text="{{translate('{num} items selected')}}"></span>
    			    </div>
    				<button type="button" class="btn btn-sm btn-primary" data-target="submit" onclick="submitModal(this)">{{translate('Submit')}}</button>
    			</div>
    		</div>
    	</div>
    </div>



@endsection

@section('modal')
    @include('modals.delete_modal')
@endsection

@section('script')

<script src="https://www.layuicdn.com/layui/layui.js"></script>
<script type="text/javascript">

        function checkAll(ctx)
        {
            let checked = $(ctx).prop('checked')
            $('input[name="id[]"]').each((i, ele) => {
                $(ele).prop('checked', checked)
            })
            if (checked) {
                $('[data-target=batchPublishModal]').removeClass('disabled')
            } else {
                $('[data-target=batchPublishModal]').addClass('disabled')
            }
        }

        function singleCheck(ctx) {
            if ($('input[name="id[]"]:checked').length > 0) {
                if ($('[data-target=batchPublishModal]').hasClass('disabled')) {
                    $('[data-target=batchPublishModal]').removeClass('disabled')
                }
            } else {
                if (!$('[data-target=batchPublishModal]').hasClass('disabled')) {
                    $('[data-target=batchPublishModal]').addClass('disabled')
                }
            }
        }

        function submitModal(ctx) {
            let id = []
            $('input[name="id[]"]').each((i, ele) => {
                if ($(ele).prop('checked')) id.push(parseInt($(ele).val()))
            })
            //let modify_op = parseInt($('select[name=modify_op] option:selected').val())
            let modify_price = $('input[name=modify_price]').val()
            if (!isNaN(modify_price)) modify_price = Number(modify_price)
            fetch('{{route('seller.products.batch_published')}}', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json; charset=utf-8',
                    'X-Requested-With': 'fetch',
                    'X-CSRF-Token': '{{ csrf_token() }}',
                },
                body: JSON.stringify({
                    _token: '{{ csrf_token() }}',
                    id,
                    modify_price,
                })
            }).then(resp => resp.json()).then(res => {
                if (res.status == 200) {
                    $('#batchPublishModal').modal('hide')
                    AIZ.plugins.notify('success', '{{ translate('Batch published updated successfully') }}');
                    setTimeout(() => {
                        window.location.reload()
                    }, 2650)
                } else {
                    AIZ.plugins.notify('danger', '{{ translate('Batch published updated failure') }}');
                }
            }).catch(err => {
                AIZ.plugins.notify('danger', '{{ translate('Updated failure') }}');
            })
        }

        function showModal(ctx) {
            if (!$(ctx).hasClass('disabled')) {
                   $('#batchPublishModal').modal('show')
                   $('#selected_tips').html( $('#selected_tips').data('text').replace('{num}', $('input[name="id[]"]:checked').length) )
                }
        }

        function docopy( id, url,price)
        {

            $.post('{{ route('products.seller.getstock') }}', {_token:'{{ csrf_token() }}', id:id},function(res){
                var html='<form id="skuform"><table>'+"<tr><td>基础售价&nbsp;&nbsp;</td><td>&nbsp;&nbsp;<input type='text' name='sprice' id='sprice' min='"+price+"' /></td></tr>";
                $.each(res.product,function(i,row ){
                    html += "<tr><td>"+row.sku+"&nbsp;&nbsp;</td><td>&nbsp;&nbsp;<input placeholder='设置SKU价格,不低于"+row.price+"' min='"+row.price+"' sku='"+row.sku+"'  type='number' name='price["+row.id+"][]' /></td></tr>";
                })


                html += "</table></form>"
                layer.open({content:html,title:'设置SKU价格',btn:['确定','取消'],yes: function(index, layero){
                      var sub = 1;
                      $.each($("#skuform").find('input'), function(ii,rr ){
                          if(   $(rr).attr('name') == 'sprice') return true;
                         min =   ($(rr).attr('min'));
                         val =   $(rr).val();
                         sku =  ($(rr).attr('sku'));
                         if( val == '' )
                         {
                             alert('请先设置属性：'+sku+' 的价格');
                             sub = 0;
                             return false;
                         }
                         if( val < min )
                         {
                             alert( "SKU:"+sku+' 价格不能低于 '+min);

                              sub = 0;return false;
                         }
                      });


                       var sprice = $("#sprice").val();
               if( sprice == '' )
                         {
                             alert('请先设置基础价格');
                             sub = 0;
                             return false;
                         }
                        if( sprice < price )
                        {
                            alert('最低价格不能低于'+ price);
                            return false;
                        }


                      if( sub == 1 )
                      {
                         location.href=url+'?'+ $("#skuform").serialize() ;
                      }
                }
                });

            },'json');


            return;
           layer.prompt({title:'输入产品售价'},function(value, index, elem){
                if( value < price )
                {
                    layer.msg('最低价格不能低于'+ price);
                    return false;
                }
                location.href = url+"?sprice="+value;
              layer.close(index);
            });
        }
        function update_featured(el){
            if(el.checked){
                var status = 1;
            }
            else{
                var status = 0;
            }
            $.post('{{ route('products.seller.featured') }}', {_token:'{{ csrf_token() }}', id:el.value, status:status}, function(data){
                if(data == 1){
                    AIZ.plugins.notify('success', '{{ translate('Featured products updated successfully') }}');
                }
                else{
                    AIZ.plugins.notify('danger', '{{ translate('Something went wrong') }}');
                }
            });
        }

        function update_published(el){
            if(el.checked){
                var status = 1;
            }
            else{
                var status = 0;
            }
            $.post('{{ route('products.published') }}', {_token:'{{ csrf_token() }}', id:el.value, status:status}, function(data){
                if(data == 1){
                    AIZ.plugins.notify('success', '{{ translate('Published products updated successfully') }}');
                }
                else{
                    AIZ.plugins.notify('danger', '{{ translate('Something went wrong') }}');
                }
            });
        }
    </script>
@endsection
